package jp.co.sharp.android.parents.kidsguard.activity.edit;

import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.bluetooth.parentble.ParentBleTransfer;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

import jp.co.sharp.android.parents.kidsguard.App;
import jp.co.sharp.android.parents.kidsguard.R;
import jp.co.sharp.android.parents.kidsguard.activity.home.HomeActivity;
import jp.co.sharp.android.parents.kidsguard.activity.profile.ProfileCameraActivity;
import jp.co.sharp.android.parents.kidsguard.activity.profile.ProfileEditActivity;
import jp.co.sharp.android.parents.kidsguard.activity.setting.SettingActivity;
import jp.co.sharp.android.parents.kidsguard.common.DealWithWaitingDlg;
import jp.co.sharp.android.parents.kidsguard.common.DelDeviceConfirmDlg;
import jp.co.sharp.android.parents.kidsguard.common.ProcessWarningDlg;
import jp.co.sharp.android.parents.kidsguard.contants.Constants;
import jp.co.sharp.android.parents.kidsguard.contants.PageSerialNumConstants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestMethodConstants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestReceiverConstants;
import jp.co.sharp.android.parents.kidsguard.dto.BluetoothReceiverDto;
import jp.co.sharp.android.parents.kidsguard.dto.ContactListDto;
import jp.co.sharp.android.parents.kidsguard.entity.KidInfoEntity;
import jp.co.sharp.android.parents.kidsguard.thread.BusinessThread;
import jp.co.sharp.android.parents.kidsguard.utils.CommonUtils;

public class ContactAddActivity extends AppCompatActivity {

    private App mApp;

    private final static int CONTACT_ADD_CODE = 1000;

    private final static int CONTACT_AVATAR_ADD_CODE = 100;

    private Boolean mOnSyncResultFlag = false;

    private EditText mNameEv;

    private ImageView mPortraitIv;

    private ImageView mDeleteIv;

    private EditText mYomiEv;

    private EditText mPhoneEv;

    private TextView mSubmitTv;

    private TextView mTitleTv;

    private ImageButton mChangeIb;

    private ImageView mBackIv;

    private String mode;

    private ContactListDto mContactListDto;

    private DelDeviceConfirmDlg mDelDeviceConfirmDlg;

    private ContactListDto mContactListOldDto;

    public ParentBleTransfer mParentBleTransfer;

    private DealWithWaitingDlg mDealWithWaitingDlg;

    private KidInfoEntity mKidInfoEntity;

    private boolean mScreenOperate = false;

    private boolean mUnReceiver = true;

    private static final String TAG = "TAG";
    // ページジャンプ
    private boolean mPageJumpFlag = false;
    // システムホームプレス
    private boolean mSystemHomeFlag = false;
    // プログラムロック
    private String mSyncLock = "syncLock";
    // 編集を再開しています...
    private boolean mEditReopening = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.i(TAG, "ContactAddActivity_onCreate");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contact_add);
        mApp = (App)getApplication();
        try {
            mounted();
        } catch (CloneNotSupportedException e) {
            Log.e(TAG,e.getMessage());
        }
        initListener();
        initReceiver();
    }

    @Override
    public void onBackPressed() {
        if (mContactListOldDto.equals(mContactListDto)){
            backToContactsActivity();
        }else {
            String message = "編集内容は保存されていません。編集内容を破棄して前の画面に戻りますか？";
            mDelDeviceConfirmDlg = new DelDeviceConfirmDlg(ContactAddActivity.this, R.style.commonDlg, message);
            mDelDeviceConfirmDlg.show();
            mDelDeviceConfirmDlg.setOnOperateSetListener(new DelDeviceConfirmDlg.OnOperateSetListener() {
                @Override
                public void onOperateSet() {
                    backToContactsActivity();
                    mDelDeviceConfirmDlg.dismiss();
                }
            });
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.i(TAG, "ContactAddActivity_onStart");
        mApp.setAppStatus(Constants.APP_STATUS_INIT);
    }
    private void mounted() throws CloneNotSupportedException {
        Log.i(TAG, "ContactAddActivity_mounted");
        mNameEv =(EditText)this.findViewById(R.id.editTextName);
        mPortraitIv=(ImageView)this.findViewById(R.id.imageViewPortrait);
        mDeleteIv = (ImageView) this.findViewById(R.id.imageViewDelete);
        mYomiEv=(EditText)this.findViewById(R.id.editTextYomi);
        mPhoneEv=(EditText)this.findViewById(R.id.editTextPhone);
        mBackIv=(ImageView)this.findViewById(R.id.imageViewBack);
        mTitleTv=(TextView)this.findViewById(R.id.tv_title);
        mSubmitTv=(TextView)this.findViewById(R.id.submitButton) ;
        mSubmitTv.setEnabled(false);
        mSubmitTv.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_reflect_normal, null));
        mChangeIb=(ImageButton)this.findViewById(R.id.imageButtonChange);
        mKidInfoEntity = ((App) getApplication()).findKidInfoBySelect();
        TextView mKidNameTv = findViewById(R.id.textViewKidName);
        String kidNameDescribe = mKidInfoEntity.getKidName()+"のキッズケータイ";
        mKidNameTv.setText(kidNameDescribe);
        mode =getIntent().getStringExtra("MODE");
        if ("EDIT".equals(mode)){
            mDeleteIv.setVisibility(View.VISIBLE);
            mContactListDto = (ContactListDto)getIntent().getSerializableExtra("INFO");
            mContactListOldDto = (ContactListDto)mContactListDto.clone();
            mNameEv.setText(mContactListDto.getName());
            mPortraitIv.setImageResource(CommonUtils.chooseImage(Integer.parseInt(mContactListDto.getPortrait())));
            mYomiEv.setText(mContactListDto.getYomi());
            mPhoneEv.setText(mContactListDto.getPhone());
            mTitleTv.setText("連絡先を編集");
        }else {
            mTitleTv.setText("連絡先を追加");
            mDeleteIv.setVisibility(View.GONE);
            mContactListDto = new ContactListDto();
            mContactListOldDto = new ContactListDto();
            mContactListOldDto.setId(-1);
            mContactListDto.setId(-1);
            mContactListOldDto.setPortrait("0");
            mContactListDto.setPortrait("0");
            mContactListOldDto.setPhone("");
            mContactListDto.setPhone("");
            mContactListOldDto.setYomi("");
            mContactListDto.setYomi("");
            mContactListOldDto.setName("");
            mContactListDto.setName("");
            mNameEv.setText("");
            mPortraitIv.setImageResource(CommonUtils.chooseImage(0));
            mYomiEv.setText("");
            mPhoneEv.setText("");
        }
    }
    @Override
    protected void onRestart() {
        super.onRestart();
        Log.i(TAG, "ContactAddActivity_onRestart");
        synchronized (mSyncLock) {
            if (mSystemHomeFlag) {
                if ((mApp.getAppStatus() != Constants.APP_STATUS_USER_PRESENT)&&(!mEditReopening)) {
                    String message = "編集を再開しています...";
                    mDealWithWaitingDlg = new DealWithWaitingDlg(ContactAddActivity.this, R.style.commonDlg, message, false);
                    mDealWithWaitingDlg.show();
                    mScreenOperate = true;
                    mEditReopening = true;
                    sendIsUsingToKid();
                    // ブロードキャストの再登録
                    unregisterReceiver(systemReceiver);
                    initReceiver();
                }
                mSystemHomeFlag = false;
            }
        }
    }
    @Override
    protected void onStop() {
        super.onStop();
        Log.i(TAG, "ContactAddActivity_onStop");
        if (!mUnReceiver) {
            synchronized (mSyncLock) {
                try {
                    unregisterReceiver(receiver);
                } catch (IllegalArgumentException e) {
                    if (e.getMessage().contains("Receiver not registered")) {
                        // Ignore this exception. This is exactly what is desired
                        Log.e(TAG, e.getMessage());
                    } else {
                        // unexpected, re-throw
                        Log.e(TAG, e.getMessage());
                    }
                }
                if (mPageJumpFlag) {
                    try {
                        unregisterReceiver(receiver);
                    } catch (IllegalArgumentException e) {
                        if (e.getMessage().contains("Receiver not registered")) {
                            // Ignore this exception. This is exactly what is desired
                            Log.e(TAG, e.getMessage());
                        } else {
                            // unexpected, re-throw
                            Log.e(TAG, e.getMessage());
                        }
                    }
                    mPageJumpFlag = false;
                }
                mUnReceiver = true;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "ContactAddActivity_onDestroy");
        if (!mUnReceiver) {
            synchronized (mSyncLock) {
                try {
                    unregisterReceiver(receiver);
                } catch (IllegalArgumentException e) {
                    if (e.getMessage().contains("Receiver not registered")) {
                        // Ignore this exception. This is exactly what is desired
                        Log.e(TAG, e.getMessage());
                    } else {
                        // unexpected, re-throw
                        Log.e(TAG, e.getMessage());
                    }
                }
                if (mPageJumpFlag) {
                    try {
                        unregisterReceiver(receiver);
                    } catch (IllegalArgumentException e) {
                        if (e.getMessage().contains("Receiver not registered")) {
                            // Ignore this exception. This is exactly what is desired
                            Log.e(TAG, e.getMessage());
                        } else {
                            // unexpected, re-throw
                            Log.e(TAG, e.getMessage());
                        }
                    }
                    mPageJumpFlag = false;
                }
                mUnReceiver = true;
            }
        }
    }
    private  void initListener(){
        Log.i(TAG, "ContactAddActivity_initListener");
        mNameEv.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {

            }
        });
        mNameEv.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//                System.out.println("s"+s.toString());
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }
            @Override
            public void afterTextChanged(Editable s) {
                mContactListDto.setName(s.toString());
                if (mContactListDto.equals(mContactListOldDto)){
                    mSubmitTv.setEnabled(false);
                    mSubmitTv.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_reflect_normal, null));
                }else {
                    mSubmitTv.setEnabled(true);
                    mSubmitTv.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_reflect_change, null));
                }
            }
        });

        //editTextYomi
//        editView.setMovementMethod(ScrollingMovementMethod.getInstance());
        mYomiEv.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {

            }
        });
        mYomiEv.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }
            @Override
            public void afterTextChanged(Editable s) {
                mContactListDto.setYomi(s.toString());
                if (mContactListDto.equals(mContactListOldDto)){
                    mSubmitTv.setEnabled(false);
                    mSubmitTv.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_reflect_normal, null));
                }else {
                    mSubmitTv.setEnabled(true);
                    mSubmitTv.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_reflect_change, null));
                }

            }
        });

        //editTextPhone
//        editView.setMovementMethod(ScrollingMovementMethod.getInstance());
        mPhoneEv.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {

            }
        });
        mPhoneEv.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//                System.out.println("s"+s.toString());
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }
            @Override
            public void afterTextChanged(Editable s) {
                mContactListDto.setPhone(s.toString());
                if (mContactListDto.equals(mContactListOldDto)){
                    mSubmitTv.setEnabled(false);
                    mSubmitTv.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_reflect_normal, null));
                }else {
                    mSubmitTv.setEnabled(true);
                    mSubmitTv.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_reflect_change, null));
                }
            }
        });

        mChangeIb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPageJumpFlag = true;
                Intent intent1 = new Intent();
                intent1.setClass(ContactAddActivity.this, ContactAvatarAddActivity.class);
                startActivityForResult(intent1, CONTACT_AVATAR_ADD_CODE);
            }
        });


        mSubmitTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                    // Dlg
                    String message = "キッズケータイへ反映中..";
                    mDealWithWaitingDlg = new DealWithWaitingDlg(ContactAddActivity.this, R.style.commonDlg, message, true);
                    mDealWithWaitingDlg.show();
                sendToKid();
            }
        });

        //imageViewBack
        mBackIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mContactListOldDto.equals(mContactListDto)){
                    backToContactsActivity();
                }else {
                    String message = "編集内容は保存されていません。編集内容を破棄して前の画面に戻りますか？";
                    mDelDeviceConfirmDlg = new DelDeviceConfirmDlg(ContactAddActivity.this, R.style.commonDlg, message);
                    mDelDeviceConfirmDlg.show();
                    mDelDeviceConfirmDlg.setOnOperateSetListener(new DelDeviceConfirmDlg.OnOperateSetListener() {
                        @Override
                        public void onOperateSet() {
                            backToContactsActivity();
                            mDelDeviceConfirmDlg.dismiss();
                        }
                    });
                }

            }
        });
        //imageViewDelete
        mDeleteIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String message = "このアラームを削除しますか？";
                mDelDeviceConfirmDlg = new DelDeviceConfirmDlg(ContactAddActivity.this, R.style.commonDlg, message);
                mDelDeviceConfirmDlg.show();
                mDelDeviceConfirmDlg.setOnOperateSetListener(() -> {
                    sendDeleteToKid();
                    mDelDeviceConfirmDlg.dismiss();
                });
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        Log.i(TAG, "ContactAddActivity_onActivityResult:"+requestCode);
        super.onActivityResult(requestCode, resultCode, intent);
        initReceiver();
        if (requestCode == CONTACT_AVATAR_ADD_CODE) {
            if (intent.hasExtra("imageIndex") && null != intent.getStringExtra("imageIndex")) {
                mPortraitIv.setImageResource(CommonUtils.chooseImage(Integer.parseInt(intent.getStringExtra("imageIndex"))));
                mContactListDto.setPortrait(intent.getStringExtra("imageIndex"));
                if (mContactListDto.equals(mContactListOldDto)){
                    mSubmitTv.setEnabled(false);
                    mSubmitTv.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_reflect_normal, null));
                }else {
                    mSubmitTv.setEnabled(true);
                    mSubmitTv.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_reflect_change, null));
                }
            }
        }
    }
    /**
     * 初期化Receiver
     */
    private void initReceiver() {
        Log.i(TAG, "ContactAddActivity_initReceiver");
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_USER_PRESENT);
        // ホームボタン
        filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        // Bluetooth
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_WRITE_DATA_CHANGED);
        registerReceiver(receiver, filter);
        registerReceiver(systemReceiver, filter);
        this.mParentBleTransfer = ((App) getApplication()).getmParentBleTransfer();
        mUnReceiver = false;
    }

    /**
     * システム放送
     */
    private final BroadcastReceiver systemReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                String action = intent.getAction();
                if (Intent.ACTION_SCREEN_OFF.equals(action)) {
                    Log.i(TAG, "ContactAddActivity_systemReceiver_ACTION_SCREEN_OFF");
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_SCREEN_OFF);
                        mScreenOperate = true;
                        sendExitToKid();
                    }
                } else if (Intent.ACTION_USER_PRESENT.equals(action)) {
                    Log.i(TAG, "ContactAddActivity_systemReceiver_ACTION_USER_PRESENT");
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_USER_PRESENT);
                        if (!mPageJumpFlag) {
                            String message = "編集を再開しています...";
                            mDealWithWaitingDlg = new DealWithWaitingDlg(ContactAddActivity.this, R.style.commonDlg, message, false);
                            mDealWithWaitingDlg.show();
                            mEditReopening = true;
                            mScreenOperate = true;
                            sendIsUsingToKid();
                            // ブロードキャストの再登録
                            unregisterReceiver(systemReceiver);
                            initReceiver();
                        }
                    }
                } else if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
                    Log.i(TAG, "ContactAddActivity_systemReceiver_ACTION_CLOSE_SYSTEM_DIALOGS");
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_CLOSE_SYSTEM_DIALOGS);
                        mSystemHomeFlag = true;
                        mScreenOperate = true;
                        sendExitToKid();
                    }
                } else if (RequestReceiverConstants.RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED.equals(action)) {
                    Log.i(TAG, "ContactAddActivity_receiver_RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED");
                    BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                    String macAddress = bluetoothReceiverDto.getAddress();
                    if (((App)getApplication()).isMimamoriCheck(macAddress)) {
                        ((App)getApplication()).addmLsIsMimamori(macAddress);
                        sendExitToKid();
                        mPageJumpFlag = true;
                        Intent intent1 = new Intent();
                        intent1.setAction(Constants.ACTION_IS_MIMAMORI);
                        intent1.setClass(ContactAddActivity.this, HomeActivity.class);
                        startActivity(intent1);
                    } else {
                        mKidInfoEntity.setBtConnStatus(Constants.DEVICE_DISCONNECTION_SUCCESS);
                        ((App)getApplication()).updateKidInfo(mKidInfoEntity);

                        String message = mKidInfoEntity.getKidName() + "と切断されました。編集を中断します。";
                        ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(ContactAddActivity.this, R.style.commonDlg, message);
                        processWarringDlg.show();
                        processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                            @Override
                            public void onOperateSet() {
                                processWarringDlg.dismiss();
                                mPageJumpFlag = true;
                                Intent intent1 = new Intent();
                                intent1.setClass(ContactAddActivity.this, SettingActivity.class);
                                startActivity(intent1);
                            }
                        });
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
            }
        }
    };

    /**
     *  is using
     */
    public void sendIsUsingToKid(){
        Log.i(TAG, "ContactAddActivity_sendIsUsingToKid");
        try{
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("method","getOperatingState");
            jsonObject.put("data",JSONObject.NULL);
            new BusinessThread(Constants.SEND_KID_IS_USING,
                    mParentBleTransfer,
                    mKidInfoEntity,
                    jsonObject,
                    PageSerialNumConstants.PAGE_SERIAL_CONTACT).start();
        }catch (JSONException e){
             Log.e(TAG,e.getMessage());
        }catch (Exception e){
             Log.e(TAG,e.getMessage());
        }
    }


    public void sendToKid(){
        Log.i(TAG, "ContactAddActivity_sendToKid");
        try {
            JSONObject jsonData = new JSONObject();
            jsonData.put("method", "addContact");
            JSONObject insertData = new JSONObject();
            insertData.put("id", mContactListDto.getId());
            insertData.put("name",mContactListDto.getName());
            insertData.put("phone",mContactListDto.getPhone());
            insertData.put("yomi",mContactListDto.getYomi());
            insertData.put("portrait",mContactListDto.getPortrait());
            jsonData.put("data", insertData);
            new BusinessThread(Constants.SEND_KID_SET_INFO,
                    mParentBleTransfer,
                    mKidInfoEntity,
                    jsonData,
                    PageSerialNumConstants.PAGE_SERIAL_CONTACT).start();
        } catch (JSONException e){
             Log.e(TAG,e.getMessage());
        }
    }

    public void sendDeleteToKid() {
        Log.i(TAG, "ContactAddActivity_sendDeleteToKid");
        try {
            JSONObject jsonData = new JSONObject();
            jsonData.put("method", "deleteContact");
            jsonData.put("data", mContactListDto.getId());
            new BusinessThread(Constants.SEND_KID_SET_INFO,
                    mParentBleTransfer,
                    mKidInfoEntity,
                    jsonData,
                    PageSerialNumConstants.PAGE_SERIAL_CONTACT).start();
        } catch (JSONException e) {
             Log.e(TAG,e.getMessage());
        }

    }

    public void sendEnterToKid(){
        Log.i(TAG, "ContactAddActivity_sendEnterToKid");
        new BusinessThread(Constants.SEND_KID_ENTER,
                mParentBleTransfer,
                mKidInfoEntity,
                null,
                PageSerialNumConstants.PAGE_SERIAL_CONTACT).start();
    }

    public void sendExitToKid(){
        Log.i(TAG, "ContactAddActivity_sendExitToKid");
        mOnSyncResultFlag = true;
        new BusinessThread(Constants.SEND_KID_EXIT,
                mParentBleTransfer,
                mKidInfoEntity,
                null,
                PageSerialNumConstants.PAGE_SERIAL_CONTACT).start();
    }
    private void backToContactsActivity() {
        Log.i(TAG, "ContactAddActivity_backToContactsActivity");
        mPageJumpFlag = true;
        Intent intent = getIntent();
        setResult(CONTACT_ADD_CODE, intent);
        finish();
    }
    private void backToEditActivity() {
        Log.i(TAG, "ContactAddActivity_backToEditActivity");
        mPageJumpFlag = true;
        Intent intent = new Intent();
        intent.setClass(this, EditActivity.class);
        startActivity(intent);
    }

    /**
     * BroadcastReceiver
     */
    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (RequestReceiverConstants.RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED.equals(action)) {
                BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                try {
                    JSONObject resp = new JSONObject(bluetoothReceiverDto.getRetStr());
                    String method = resp.getString("method");
                    Log.i(TAG, "ContactAddActivity_receiver_RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED");
                    if (null != method) {
                       if (RequestMethodConstants.METHOD_GET_OPERATING_STATE.equals(method)) {
                            JSONObject data = resp.getJSONObject("data");
                           Log.i(TAG, "ContactAddActivity_receiver_RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED_getOperatingState:"+data.toString());
                           if (Constants.IS_USING_OK.equals(data.getString("state"))) {
                                sendEnterToKid();
                            }else {
                                handler.sendEmptyMessage(0);
                                String message = "別のスマートフォンから操作中のため、設定を変更できません。";
                                ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(ContactAddActivity.this, R.style.commonDlg, message);
                                processWarringDlg.show();
                                processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                                    @Override
                                    public void onOperateSet() {
                                        processWarringDlg.dismiss();
                                        // ページジャンプ
                                        mPageJumpFlag = true;
                                        ContactAddActivity.this.finish();
                                    }
                                });
                            }
                       } else if (RequestMethodConstants.METHOD_ON_SYNC_RESULT.equals(method)) {
                           Log.i(TAG, "ContactAddActivity_receiver_RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED_onSyncResult");
                            if (Constants.ON_SYNC_RESULT.equals(resp.getString("result"))) {
                                handler.sendEmptyMessage(0);
                                backToContactsActivity();
                            }else {
                                handler.sendEmptyMessage(0);
                                String message = "キッズケータイへ反映できませんでした";
                                ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(ContactAddActivity.this, R.style.commonDlg, message);
                                processWarringDlg.show();
                                processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                                    @Override
                                    public void onOperateSet() {
                                        processWarringDlg.dismiss();
                                    }
                                });
                            }
                       }else if (RequestMethodConstants.METHOD_ON_OPERATE_INTERRUPT.equals(method)){
                           Log.i(TAG, "ContactAddActivity_receiver_RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED_onOperateInterrupt");
                           String message = "キッズケータイが操作されました。編集を中断します。";
                           ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(ContactAddActivity.this, R.style.commonDlg, message);
                           processWarringDlg.show();
                           processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                               @Override
                               public void onOperateSet() {
                                   processWarringDlg.dismiss();
                                   backToEditActivity();
                               }
                           });
                       }
                    }
                } catch (JSONException e) {
                     Log.e(TAG,e.getMessage());
                }

            } else if (RequestReceiverConstants.RECEIVER_BLUETOOTH_WRITE_DATA_CHANGED.equals(action)) {
                Log.i(TAG, "ContactAddActivity_receiver_RECEIVER_BLUETOOTH_WRITE_DATA_CHANGED");
                //isFinish
                BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                if (bluetoothReceiverDto.isFinished()) {
                    if (mOnSyncResultFlag) {
                        mOnSyncResultFlag = false;
                        if (!mScreenOperate) {
                            backToContactsActivity();
                        }
                    }
                    if (!mScreenOperate) {

                    } else {
                        mScreenOperate = false;
                        mEditReopening = false;
                        handler.sendEmptyMessage(0);
                    }

                }

            }
        }
    };




    /**
     * Dialog閉じる
     */
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (null != mDealWithWaitingDlg && mDealWithWaitingDlg.isShowing()) {
                mDealWithWaitingDlg.dismiss();
            }
        }
    };

}
